package com.partner.share.work.mq.producer;

import com.partner.share.work.mq.config.ActiveProperties;
import com.partner.share.work.mq.construction.ActiveMQTopicConst;
import com.partner.share.work.mq.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jms.JmsProperties;

import javax.jms.*;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2019年09月30日 15:04:00
 */
@Slf4j
public class Producer {


    private Destination destination = null;

    private Connection connection = null;

    private Session session = null;

    private MessageProducer producer = null;

    /**
     *  初始化生产者
     * @param destinationName 队列名称
     * @throws JMSException 异常
     */
    private void init(String destinationName) throws JMSException {
        //ActiveProperties activeProperties = SpringContextHolder.getBean("activeProperties",ActiveProperties.class);
        // 连接工厂是用户创建连接的对象.
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory( "admin", "admin", "tcp://127.0.0.1:61616/");
        //创建连接对象
        connection = connectionFactory.createConnection();
        // 创建会话用于创建消息的生产者，消费者和消息。是生产和消费的一个单线程上下文。
        session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        //客户用来指定他生产消息的目标还有他消费消息的来源的对象. (主题类型类似广播)
        destination = session.createQueue(destinationName);
        //消息生产者
        producer = session.createProducer(destination);
        // 不持久化消息
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    public synchronized void sendMessage(String destinationName, String message,String user) throws JMSException {
        init(destinationName);
        connection.start();
        TextMessage msg = session.createTextMessage();
        msg.setText(user+":"+message);
        producer.send(msg);
        log.info("({}){}发布了一条主题【{}】消息{}。",this,user, destinationName, message);

    }

    public void close() throws JMSException {
        if (producer!=null){
            producer.close();
        }
        if (session!=null){
            session.close();
        }
        if (connection!=null){
            connection.close();
        }
        log.info("生产者已关闭");
    }
}
